package cn.itlaobing.controller;

import cn.itlaobing.model.Material;
import cn.itlaobing.service.uploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin(value = "http://127.0.0.1:8848")
public class UploadController {
    @Autowired
    uploadService uploadService;

    @PostMapping("/upload")
    public Map<String , Object> fileUpload(MultipartFile file , HttpServletRequest req ,Material material){
        Map<String , Object> result = new HashMap<>();
        String originalFilename = file.getOriginalFilename();
        String lastName = originalFilename.substring(originalFilename.lastIndexOf("."));
//        if (originalFilename.endsWith(".jpg")){
//            result.put("status" , "error");
//            result.put("message" , "文件类型不支持");
//            return result;
//        }
        String realPath = req.getServletContext().getRealPath("/") ;
        File file1 = new File(realPath);
        if (!file1.exists()) {
            file1.mkdir();
        }
        String filename = UUID.randomUUID().toString() + lastName;
        try {
            file.transferTo(new File(file1 , filename));
            material.setPath(req.getScheme() + "://" +req.getServerName() + ":" + req.getServerPort() + "/" + filename);
            uploadService.insert(material);
            result.put("status" , "success");
            result.put("url" , material.getPath());

        } catch (IOException e) {
            result.put("status" , "error");
            result.put("message" , e.getMessage());
        }
        return result;
    }
}
